﻿using System.IO;
using System.Xml.Serialization;

public static class Serializator
{
	public static T FromFileToModel<T>(string filename)
	{
		using (var sr = new StreamReader(filename))
		{
			T t;
			try { t = FromStreamToModel<T>(sr.BaseStream); }
			finally { sr.Close(); }
			return t;
		}
	}
	public static T FromBytesToModel<T>(this byte[] data) where T : class, new()
	{
		var stream = new MemoryStream(data);
		stream.Flush();
		stream.Position = 0;
		return FromStreamToModel<T>(stream);
	}
	public static T FromStreamToModel<T>(Stream stream)
	{
		var xs = new XmlSerializer(typeof(T));
		return (T)xs.Deserialize(stream);
	}
	public static T FromStringToModel<T>(this string str) where T : class
	{
		using (var sr = new StringReader(str))
		{
			var xs = new XmlSerializer(typeof(T));
			return (T)xs.Deserialize(sr);			
		}
	}
	public static bool IsModelDeserializable<T>(this string str) where T : class
	{
		try
		{
			FromStringToModel<T>(str);
			return true;
		}
		catch
		{
			return false;
		}
		
	}

	public static void ModelToFile<T>(this T model, string filename)
	{
		using (var fs = new FileStream(filename, FileMode.Create))
		{
			try
			{
				new XmlSerializer(typeof(T)).Serialize(fs, model);
			}
			finally
			{
				fs.Flush();
				fs.Close();
			}
		}
	}
	public static byte[] ModelToBytes<T>(this T model)
	{
		var stream = ModelToStream(model);
		return stream.ToArray();
	}
	public static string ModelToString<T>(this T model)
	{
		using (var sw = new StringWriter())
		{
			var xs = new XmlSerializer(typeof(T));
			xs.Serialize(sw, model);
			return sw.ToString();
		}
	}
	public static MemoryStream ModelToStream<T>(this T model)
	{
		var stream = new MemoryStream();
		var xs = new XmlSerializer(typeof(T));
		xs.Serialize(stream, model);
		stream.Flush();
		stream.Position = 0;
		return stream;
	}
}

